package com.pickgliss.loader
{
	import flash.events.Event;
	import flash.events.EventDispatcher;

	public class LoaderQueue extends EventDispatcher
	{
		private var _loaders:Vector.<BaseLoader>;
		public function LoaderQueue()
		{
			_loaders = new Vector.<BaseLoader>();
		}
		
		public function addLoader(loader:BaseLoader):void
		{
			_loaders.push(loader);
		}
		
		public function start():void
		{
			var count:int = _loaders.length;
			for(var i:int = 0;i<count;i++)
			{
				if(_loaders == null)return;
				_loaders[i].addEventListener(LoaderEvent.COMPLETE,__loadComplete);
				LoaderManager.Instance.startLoad(_loaders[i]);
			}
		}
		
		public function dispose():void
		{
			removeEvent();
			_loaders = null;
		}
		
		public function removeEvent():void
		{
			for(var i:int = 0;i<_loaders.length;i++)
			{
				_loaders[i].removeEventListener(LoaderEvent.COMPLETE,__loadComplete);
			}
		}
		
		public function get length():int
		{
			return _loaders.length;
		}
		
		public function get loaders():Vector.<BaseLoader>
		{
			return _loaders;
		}
		
		private function __loadComplete(event:LoaderEvent):void
		{
			event.loader.removeEventListener(LoaderEvent.COMPLETE,__loadComplete);
			if(isComplete)
			{
				removeEvent();
				dispatchEvent(new Event(Event.COMPLETE));
			}
			
		}
		
		public function get isComplete():Boolean
		{
			for(var i:int = 0;i<_loaders.length;i++)
			{
				if(!_loaders[i].isComplete)return false;
			}
			return true;
		}
	}
}